/*
 * Copyright (c) 2020 hebeiyiliuba.com
 * All rights reserved.
 *
 */
package org.jeecg.modules.wlhy.report.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.enums.ReportPlatformEnum;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.IDUtils;
import org.jeecg.modules.third.jg.report.freight.information.constant.enums.AhUploadStatusEnum;
import org.jeecg.modules.third.jg.report.freight.information.dto.AppInfoDTO;
import org.jeecg.modules.third.jg.xz.park.XzIndustrialParkService;
import org.jeecg.modules.third.jg.xz.park.dto.*;
import org.jeecg.modules.third.jg.xz.park.dto.payment.XzPaymentDTO;
import org.jeecg.modules.third.jg.xz.park.dto.resp.*;
import org.jeecg.modules.third.jg.xz.park.dto.shippingnote.XzShippingNoteDTO;
import org.jeecg.modules.third.openapi.WaybillRouteService;
import org.jeecg.modules.wlhy.bill.entity.HyShippingNoteBill;
import org.jeecg.modules.wlhy.bill.service.IHyShippingNoteBillService;
import org.jeecg.modules.wlhy.hycarrier.entity.HyCarrierReport;
import org.jeecg.modules.wlhy.hycarrier.service.IHyCarrierReportService;
import org.jeecg.modules.wlhy.hyconfig.entity.HyConfig;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriverReport;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverReportService;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverService;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicle;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicleReport;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicleType;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleReportService;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleService;
import org.jeecg.modules.wlhy.report.IReportService;
import org.jeecg.modules.wlhy.shipping.constant.ShippingPayStatus;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingParkReport;
import org.jeecg.modules.wlhy.shipping.entity.UpDataShippingNoteDTO;
import org.jeecg.modules.wlhy.shipping.entity.WaybillRouteVO;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingParkReportService;
import org.jeecg.modules.wlhy.utils.HyCfgUtil;
import org.jeecg.modules.wlhy.utils.HyConfigUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @BelongsPackage: org.jeecg.modules.wlhy.report.impl
 * @Author: duanlikao
 * @CreateTime: 2023-03-08 16:44
 * @Description:
 * @Version: 1.0
 */
@Service
@Slf4j
public class YuanqvReportService implements IReportService {

    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;

    @Value(value = "${jeecg.path.bank}")
    private String bankpath;

    @Autowired
    private WaybillRouteService waybillRouteService;

    @Resource
    private BaseReportService baseReportService;

    @Resource
    private IHyDriverService driverService;

    @Resource
    private IHyVehicleService vehicleService;

    @Resource
    private IHyDriverReportService hyDriverReportService;

    @Resource
    private IHyVehicleReportService vehicleReportService;

    @Resource
    private IHyCarrierReportService hyCarrierReportService;

    @Resource
    private XzIndustrialParkService xzIndustrialParkService;

    @Autowired
    private IHyShippingNoteService hyShippingNoteService;

    @Autowired
    private IHyShippingNoteBillService hyShippingNoteBillService;

    @Autowired
    private IHyShippingParkReportService hyShippingParkReportService;

    @Override
    public ReportPlatformEnum getReportType() {
        return ReportPlatformEnum.REPORT_PLATFORM_XZ;
    }

    @Override
    public void checkReport() {
        //产业园平台
        if(!HyCfgUtil.isUsed2("yuanqu_report")){
            throw new JeecgBootException("园区监管平台未配置参数!");
        }
    }

    @Override
    public AppInfoDTO getAppInfo() {
        return null;
    }

    @Override
    public boolean report(HyShippingNote hyShippingNote) {
        return true;
    }

    @Override
    public Result reportShippingNote(HyShippingNote hyShippingNote) {
        Result result = this.checkDriverAndVehicle(hyShippingNote.getId());
        if (!result.getCode().equals(CommonConstant.SC_OK_200)) {
            return result;
        }

        return this.uploadXzShippingNote(hyShippingNote);
    }


    @Override
    public Result reportCapitalFlow(HyShippingNote hyShippingNote) {
        Result result = this.checkDriverAndVehicle(hyShippingNote.getId());
        if (!result.getCode().equals(CommonConstant.SC_OK_200)) {
            return result;
        }

        return this.uploadXzCapitalFlow(hyShippingNote.getId(), null);
    }

    @Override
    public Result reportCapitalFlow(HyShippingNote hyShippingNote, String uploadBankHdImg) {
        Result result = this.checkDriverAndVehicle(hyShippingNote.getId());
        if (!result.getCode().equals(CommonConstant.SC_OK_200)) {
            return result;
        }

        return this.uploadXzCapitalFlow(hyShippingNote.getId(), uploadBankHdImg);
    }

    //上报运单和资金流水前，先确认司机、车辆的上传状态
    private Result checkDriverAndVehicle(String shippingId) {

        HyShippingNote hyShippingNote = this.hyShippingNoteService.getById(shippingId);
        if (null == hyShippingNote) {
            return Result.error("运单不存在");
        }

        String driverId = hyShippingNote.getDriverId();
        String vehicleId = hyShippingNote.getVehicleId();
        if (StrUtil.isEmpty(driverId)) {
            return Result.error("当前运单司机信息不存在");
        }

        if (StrUtil.isEmpty(vehicleId)) {
            return Result.error("当前运单车辆信息不存在");
        }

        //自动上报司机和车辆配置
        String autoUpload = HyCfgUtil.getCfgItem2("yuanqu_report","auto_upload");

        boolean bDriverUploadStatus = this.hyDriverReportService.checkUploadStatus(driverId, "2000",
                ReportPlatformEnum.REPORT_PLATFORM_XZ.getCode());
        if (!bDriverUploadStatus) {
            if (StrUtil.isEmpty(autoUpload) || !autoUpload.equals("1")) {
                return Result.error("请先同步司机数据");
            }
            log.warn("司机未上报园区平台，开始同步司机数据, {}", driverId);
            Result dResult = this.uploadDriver(driverId);
            if (!dResult.getCode().equals(CommonConstant.SC_OK_200)) {
                return dResult;
            }
        }

        boolean bVehicleUploadStatus = this.vehicleReportService.checkUploadStatus(vehicleId, "2000",
                ReportPlatformEnum.REPORT_PLATFORM_XZ.getCode());
        if (!bVehicleUploadStatus) {
            if (StrUtil.isEmpty(autoUpload) || !autoUpload.equals("1")) {
                return Result.error("请先同步车辆数据");
            }
            log.warn("车辆未上报园区平台，开始同步车辆数据, {}", vehicleId);
            Result vResult = this.uploadVehicle(vehicleId);
            if (!vResult.getCode().equals(CommonConstant.SC_OK_200)) {
                return vResult;
            }
        }

        String heilongjiangPark = HyCfgUtil.getCfgItem2("yuanqu_report","heilongjiang_park");
        if (StrUtil.isNotEmpty(heilongjiangPark)) {

            HyDriver hyDriverDb = driverService.getById(driverId);
            if (hyDriverDb == null) {
                return Result.error("未找到对应司机数据");
            }

            HyVehicle hyVehicleDb = vehicleService.getById(vehicleId);
            if (hyVehicleDb == null) {
                return Result.error("未找到对应车辆数据");
            }

            HyCarrierReport hyCarrierReport = this.hyCarrierReportService.getUploadStatus(driverId, "2000",
                    ReportPlatformEnum.REPORT_PLATFORM_XZ.getCode());
            //上报实际承运人
            if (null == hyCarrierReport || !"1".equals(hyCarrierReport.getCarrierUploadStatus())) {
                Result r = this.uploadCarrier(hyDriverDb);
                if (!r.getCode().equals(CommonConstant.SC_OK_200)) {
                    return r;
                }
            }

            //上报实际承运人关联车辆
            if (null == hyCarrierReport || !"1".equals(hyCarrierReport.getCarrierVehicleUploadStatus())) {
                Result r = this.uploadCarrierVehicle(hyDriverDb, hyVehicleDb);
                if (!r.getCode().equals(CommonConstant.SC_OK_200)) {
                    return r;
                }
            }

//            //上报实际承运人关联驾驶员
//            if (null == hyCarrierReport || !"1".equals(hyCarrierReport.getCarrierDriverUploadStatus())) {
//                Result r = this.uploadCarrierDriver(hyDriverDb);
//                if (!r.getCode().equals(CommonConstant.SC_OK_200)) {
//                    return r;
//                }
//            }
        }

        return Result.OK();
    }

    /**
     * 产业园区
     */
    public Result uploadXzCapitalFlow(String shippingId, String uploadBankHdImg) {

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("shipping_id", shippingId);
        List<HyShippingNoteBill> shippingNoteBills = hyShippingNoteBillService.list(queryWrapper);

        if (CollectionUtils.isEmpty(shippingNoteBills) ) {
            throw new JeecgBootException("未找到对应数据");
        }

        HyShippingNote hyShippingNote = this.hyShippingNoteService.getById(shippingId);
        if (!hyShippingNote.getShippingPayStatus().equals(ShippingPayStatus.支付完成.getValue())) {
            return Result.error("该运单未支付完成");
        }

        HyShippingParkReport existParkReport = this.hyShippingParkReportService.getById(shippingId);
        if (null == existParkReport) {
            throw new JeecgBootException("请先上报运单数据到园区监管平台");
        }
        //1表示上报成功，3表示等待校验，如果不是这2个状态说明运单没有上报过
        if (!"1".equals(existParkReport.getUploadStatus()) && !"3".equals(existParkReport.getUploadStatus())) {
            throw new JeecgBootException("请先上报运单数据到园区监管平台");
        }

        String needPDF = HyCfgUtil.getCfgItem2("yuanqu_report","need_pdf");
        if (StrUtil.isNotEmpty(needPDF)) {
            for (HyShippingNoteBill shippingNoteBill : shippingNoteBills) {
                String bankHdPDF = bankpath + File.separator + shippingNoteBill.getBankHd();
                if (StringUtils.isEmpty(bankHdPDF)) {
                    throw new JeecgBootException("该运单银行回单信息不存在！" + bankHdPDF);
                }

                File file = new File(bankHdPDF);
                if (!file.exists()) {
                    throw new JeecgBootException("该运单银行回单文件不存在！" + bankHdPDF);
                }

                String payFile = xzIndustrialParkService.uploadFile(bankHdPDF, "运单支付凭证(回单)");
                if (StringUtils.isBlank(payFile)) {
                    throw new JeecgBootException("该运单银行回单文件上传失败！");
                }

                shippingNoteBill.setBankHd(payFile);
            }

        } else {
            //支持手工上传回单文件，如果uploadBankHdImg不为空说明从前端选择过图片上传
            if (StrUtil.isNotEmpty(uploadBankHdImg)) {
                uploadBankHdImg = uploadpath + File.separator + uploadBankHdImg;
                File file = new File(uploadBankHdImg);
                if (!file.exists()) {
                    throw new JeecgBootException("未找到该运单上传的回单文件，" + uploadBankHdImg);
                }

                String payFile = xzIndustrialParkService.uploadFile(uploadBankHdImg, "运单支付凭证(回单)");
                if (StringUtils.isBlank(payFile)) {
                    throw new JeecgBootException("该运单银行回单文件上传失败！");
                }

                for (HyShippingNoteBill shippingNoteBill : shippingNoteBills) {
                    shippingNoteBill.setBankHd(payFile);
                }

            } else {
                for (HyShippingNoteBill shippingNoteBill : shippingNoteBills) {
                    String bankHdImg = StringUtils.isNotBlank(shippingNoteBill.getBankHd()) ?
                            bankpath + File.separator + shippingNoteBill.getBankHd() :
                            uploadpath + File.separator + shippingNoteBill.getBankHdImg();

                    if (StringUtils.isEmpty(bankHdImg)) {
                        throw new JeecgBootException("该运单银行回单信息不存在！" + bankHdImg);
                    }
                    //String pathTmp =  uploadpath  + File.separator + bankHdImg;
                    ////文件名是pdf改成jpg
                    //String suffix = bankHdImg.substring(bankHdImg.lastIndexOf("."));
                    //if(".pdf".equals(suffix)){
                    //    pathTmp =  uploadpath  + File.separator + bankHdImg.substring(0, bankHdImg.lastIndexOf(".")) + ".jpg";
                    //    File file = new File(pathTmp);
                    //    if (!file.exists()) {
                    //        pathTmp =  bankpath  + File.separator +  bankHdImg.substring(0, bankHdImg.lastIndexOf(".")) + ".jpg";
                    //    }
                    //}
                    File file = new File(bankHdImg);
                    if (!file.exists()) {
                        throw new JeecgBootException("该运单银行回单文件不存在！" + bankHdImg);
                    }

                    String payFile = xzIndustrialParkService.uploadFile(bankHdImg, "运单支付凭证(回单)");
                    if (StringUtils.isBlank(payFile)) {
                        throw new JeecgBootException("该运单银行回单文件上传失败！");
                    }

                    shippingNoteBill.setBankHd(payFile);
                }
            }
        }

        HyShippingParkReport hyShippingParkReport = new HyShippingParkReport();
        hyShippingParkReport.setId(shippingId);
        hyShippingParkReport.setShippingId(shippingId);
        hyShippingParkReport.setZjUploadDate(new Date());
        hyShippingParkReport.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_XZ.getCode());

        XzPaymentDTO paymentDTO = baseReportService.getXzFinancialDTO(shippingNoteBills, hyShippingNote);
        try {
            XzApiBaseResDTO xzApiBaseResDTO = xzIndustrialParkService.waybillPayment(paymentDTO);
            if (1001 == xzApiBaseResDTO.getStatus().intValue() || 2018 == xzApiBaseResDTO.getStatus().intValue()) {
                //这里不用异步event事件，用同步的方式延时3秒验证运单
                hyShippingParkReport.setZjUploadStatus("1");
                this.hyShippingParkReportService.saveOrUpdate(hyShippingParkReport);
                Thread.sleep(1000);
                return this.validateShippingNote(hyShippingNote);
            } else {
                String result = JSONObject.toJSONString(xzApiBaseResDTO.getResult());
                hyShippingParkReport.setUploadStatus("2");
                hyShippingParkReport.setFailureReason(xzApiBaseResDTO.getMessage() + result);
                this.hyShippingParkReportService.saveOrUpdate(hyShippingParkReport);
            }
        } catch (Exception e) {
            hyShippingParkReport.setUploadStatus("2");
            hyShippingParkReport.setFailureReason(e.getMessage());
            this.hyShippingParkReportService.saveOrUpdate(hyShippingParkReport);
        }

        return Result.error("上报资金流水发生错误");
    }


    /**
     * 产业园平台上报电子运单
     *
     * @param hyShippingNote
     * @return
     */
    public Result uploadXzShippingNote(HyShippingNote hyShippingNote) {

        HyShippingNote ShippingNoteDb = hyShippingNoteService.getById(hyShippingNote.getId());
        if (ShippingNoteDb == null) {
            throw new JeecgBootException("未找到对应数据");
        }

        if (StringUtils.isBlank(ShippingNoteDb.getShippingContract())) {
            throw new JeecgBootException("运单合同不为空,请补充运单合同");
        }

        String needPay = HyCfgUtil.getCfgItem2("yuanqu_report","need_pay");
        if (StrUtil.isNotEmpty(needPay)) {
            if (!ShippingNoteDb.getShippingPayStatus().equals(ShippingPayStatus.支付完成.getValue())) {
                return Result.error("该运单未支付完成，请支付后再上传运单");
            }
        }

        HyVehicle hyVehicle = this.vehicleService.getById(ShippingNoteDb.getVehicleId());
        String needTrace = HyCfgUtil.getCfgItem2("yuanqu_report","need_trace");
        if (StrUtil.isNotEmpty(needTrace)) {
            String startTime = DateUtils.dateTimeToString(ShippingNoteDb.getStatusDtReceive());
            String endTime = DateUtils.dateTimeToString(ShippingNoteDb.getStatusDtUnloading());
            String vehicleColor = StringUtils.isNotEmpty(hyVehicle.getVehiclePlateColorCode()) ? hyVehicle.getVehiclePlateColorCode() : "2";
            WaybillRouteVO waybillRouteVO = this.waybillRouteService.getWaybillRoute(hyVehicle.getVehicleNumber(), vehicleColor, startTime, endTime, "GCJ02");
            //如果轨迹是空或者是0km无法进行上报
            if (StrUtil.isEmpty(waybillRouteVO.getMileage()) || 0 == Double.valueOf(waybillRouteVO.getMileage()).intValue()) {
                log.info("无法获取运单的运输距离，请检查中交车辆轨迹{} {}", ShippingNoteDb.getShippingNoteNumber(), waybillRouteVO.getMileage());
                return Result.error("无法获取运单的运输距离，请检查中交车辆轨迹。");
            }

            log.info("园区运单上报，获取中交运输距离{} {}", ShippingNoteDb.getShippingNoteNumber(), waybillRouteVO.getMileage());
        }

        if (!validateVehicle(hyVehicle, "2000")) {
            throw new JeecgBootException("该运单车辆未在园区系统校验通过，请登录园区系统查看原因");
        }

        HyDriver hyDriver = this.driverService.getById(ShippingNoteDb.getDriverId());
        if (!validateDriver(hyDriver, "2000")) {
            throw new JeecgBootException("该运单司机未在园区系统校验通过，请登录园区系统查看原因");
        }

//非必填
//        if (StringUtils.isBlank(hyShippingNote.getLoadingSceneImg())) {
//            throw new JeecgBootException("运单装货现场照片不为空,请补充信息");
//        }
//
//        if (StringUtils.isBlank(hyShippingNote.getUnloadingSceneImg())) {
//            throw new JeecgBootException("运单卸货现场照片不为空,请补充信息");
//        }
//        if (!"2".equals(hyShippingNote.getUploadStatus())) {
//            baseReportService.checkShippingNoteRoute(hyShippingNote);
//        }
        //Date nowDate = new Date();
        //Calendar c = Calendar.getInstance();
        //c.setTime(ShippingNoteDb.getStatusDtUnloading());
        //c.add(Calendar.HOUR_OF_DAY, 6);
        //Date statusDtUnloading = c.getTime();
        //if(nowDate.after(statusDtUnloading)){
        //    throw new JeecgBootException("运单上报时间必须在交货时间后前后6小时上报");
        //}

        HyShippingParkReport hyShippingParkReport = this.hyShippingParkReportService.getById(hyShippingNote.getId());
        if (null != hyShippingParkReport && "1".equals(hyShippingParkReport.getUploadStatus())) {
            return Result.OK("运单已上报，请勿重复上报");
        }

        if (null == hyShippingParkReport) {
            hyShippingParkReport = new HyShippingParkReport();
        }

        hyShippingParkReport.setId(ShippingNoteDb.getId());
        hyShippingParkReport.setShippingId(ShippingNoteDb.getId());
        hyShippingParkReport.setShippingNoteNumber(ShippingNoteDb.getShippingNoteNumber());
        hyShippingParkReport.setUploadDate(new Date());
        hyShippingParkReport.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_XZ.getCode());

        XzShippingNoteDTO xzShippingNoteDTO = baseReportService.shippingNoteTOXzShippingNoteDTO(ShippingNoteDb, hyShippingNote.getCompanyId());
        try {
            XzApiBaseResDTO xzApiBaseResDTO = xzIndustrialParkService.waybillShippingNote(xzShippingNoteDTO);
            if (1001 == xzApiBaseResDTO.getStatus().intValue()) {
                hyShippingParkReport.setUploadStatus("1");
                this.hyShippingParkReportService.saveOrUpdate(hyShippingParkReport);
                return Result.OK("上报成功");
            } else if (2018 == xzApiBaseResDTO.getStatus().intValue()) {
                hyShippingParkReport.setUploadStatus("3");
                hyShippingParkReport.setFailureReason("上传完成,等待系统校验");
                this.hyShippingParkReportService.saveOrUpdate(hyShippingParkReport);
                return Result.OK("上报成功");
            } else {
                String result = JSONObject.toJSONString(xzApiBaseResDTO.getResult());
                hyShippingParkReport.setUploadStatus("2");
                hyShippingParkReport.setFailureReason(xzApiBaseResDTO.getMessage() + result);
                this.hyShippingParkReportService.saveOrUpdate(hyShippingParkReport);
                return Result.error("上报失败: " + xzApiBaseResDTO.getMessage() + result);
            }
        } catch (Exception e) {
            hyShippingParkReport.setUploadStatus("2");
            hyShippingParkReport.setFailureReason(e.getMessage());
            this.hyShippingParkReportService.saveOrUpdate(hyShippingParkReport);
        }

        return Result.error("运单上报过程中出现错误");
    }


    /**
     * 车辆信息校验结果查询接口
     * @param hyVehicle
     * @return
     */
    private boolean validateVehicle(HyVehicle hyVehicle, String companyId) {
        List <ValidateVehicleDTO> validateVehicleDTOS = Collections.singletonList(
                new ValidateVehicleDTO()
                        .setVehicleNumber(hyVehicle.getVehicleNumber())
                        .setVehiclePlateColorCode(hyVehicle.getVehiclePlateColorCode())
        );
        XzApiBaseResDTO  xzApiBaseResDTO = xzIndustrialParkService.validateVehicle(validateVehicleDTOS);
        if(xzApiBaseResDTO.isSuccess() && 1001 == xzApiBaseResDTO.getStatus()){

            String result = JSONObject.toJSONString(xzApiBaseResDTO.getResult());
            if(StringUtils.isBlank(result)){
                throw new JeecgBootException("效验车辆异常请稍后再试");
            }
            List<VehicleValidate> vehicleValidates = JSONObject.parseArray(result, VehicleValidate.class);
            VehicleValidate vehicleValidate  = vehicleValidates.get(0);
            if(vehicleValidate.getValidateStatus().contains("通过")){
                return true;
            }else {
                List<ValidateResult> validateResults = vehicleValidate.getValidateResult().stream()
                        .filter(a -> a.getFlag().equals("异常")).collect(
                                Collectors.toList());
                HyVehicleReport hyVehicleReport = new HyVehicleReport();
                //hyVehicleReport.setId(hyVehicle.getId());
                hyVehicleReport.setVehicleId(hyVehicle.getId());
                hyVehicleReport.setCompanyId(companyId);
                hyVehicleReport.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_XZ.getCode());
                hyVehicleReport.setVehicleUploadStatus( "2");
                hyVehicleReport.setUploadDate( new Date() );
                hyVehicleReport.setVehicleReportFailureReason(JSONObject.toJSONString(validateResults));
                vehicleReportService.saveVehicleReport(hyVehicleReport);
                return false;
            }
        }else {
            String result = JSONObject.toJSONString(xzApiBaseResDTO.getResult());
            throw new JeecgBootException(xzApiBaseResDTO.getMessage()+result);
        }
    }


    /**
     * 驾驶员信息校验结果查询接口
     * @param hyDriver
     * @return
     */
    private boolean validateDriver(HyDriver hyDriver, String companyId) {

        List<ValidateDriverDTO> validateDriverDTOS = Collections.singletonList(
                new ValidateDriverDTO().setDrivingLicense(hyDriver.getIdcard())
        );
        XzApiBaseResDTO  xzApiBaseResDTO = xzIndustrialParkService.validateDriver(validateDriverDTOS);
        if(xzApiBaseResDTO.isSuccess() && 1001 == xzApiBaseResDTO.getStatus()){

            String result = JSONObject.toJSONString(xzApiBaseResDTO.getResult());
            if(StringUtils.isBlank(result)){
                throw new JeecgBootException("校验司机异常请稍后再试");
            }
            List<TransDriver> transDrivers = JSONObject.parseArray(result, TransDriver.class);
            TransDriver transDriver = transDrivers.get(0);
            if(transDriver.getValidateStatus().contains("通过")){
                return true;
            }else {
                List<ValidateResult> validateResults = transDriver.getValidateResult().stream()
                        .filter(a -> a.getFlag().equals("异常")).collect(
                                Collectors.toList());
                HyDriverReport hyDriverReport = new HyDriverReport();
                //hyDriverReport.setId(hyDriver.getId());
                hyDriverReport.setDriverId(hyDriver.getId());
                hyDriverReport.setCompanyId(companyId);
                hyDriverReport.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_XZ.getCode());
                hyDriverReport.setDriverUploadStatus( "2");
                hyDriverReport.setUploadDate( new Date() );
                hyDriverReport.setDriverReportFailureReason(JSONObject.toJSONString(validateResults));
                hyDriverReportService.saveDriverReport(hyDriverReport);

                return false;
            }
        }else {
            String result = JSONObject.toJSONString(xzApiBaseResDTO.getResult());
            throw new JeecgBootException(xzApiBaseResDTO.getMessage()+result);
        }

    }


    /**
     * 实际承运人信息校验结果查询接口
     * @param hyDriver
     * @return
     */
    private boolean validateCarrier(HyDriver hyDriver, String companyId) {

        List<ValidateCarrierDTO> ValidateCarrierDTOS = Collections.singletonList(
                new ValidateCarrierDTO().setCarrierLicense(hyDriver.getIdcard())
        );
        XzApiBaseResDTO xzApiBaseResDTO = xzIndustrialParkService.validateCarrier(ValidateCarrierDTOS);
        if (xzApiBaseResDTO.isSuccess() && 1001 == xzApiBaseResDTO.getStatus()) {
            String result = JSONObject.toJSONString(xzApiBaseResDTO.getResult());
            if (StringUtils.isBlank(result)) {
                throw new JeecgBootException("校验承运人异常请稍后再试");
            }

            log.warn("校验承运人结果：{}", result);
            return true;
//            List<TransDriver> transDrivers = JSONObject.parseArray(result, TransDriver.class);
//            TransDriver transDriver = transDrivers.get(0);
//            if (transDriver.getValidateStatus().contains("通过")){
//                return true;
//            } else {
//                List<ValidateResult> validateResults = transDriver.getValidateResult().stream()
//                        .filter(a -> a.getFlag().equals("异常")).collect(
//                                Collectors.toList());
//                HyDriverReport hyDriverReport = new HyDriverReport();
//                hyDriverReport.setDriverId(hyDriver.getId());
//                hyDriverReport.setCompanyId(companyId);
//                hyDriverReport.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_XZ.getCode());
//                hyDriverReport.setDriverUploadStatus( "2");
//                hyDriverReport.setUploadDate( new Date() );
//                hyDriverReport.setDriverReportFailureReason(JSONObject.toJSONString(validateResults));
//                hyDriverReportService.saveDriverReport(hyDriverReport);
//                return false;
//            }
        } else {
            String result = JSONObject.toJSONString(xzApiBaseResDTO.getResult());
            throw new JeecgBootException(xzApiBaseResDTO.getMessage()+result);
        }
    }

    /**
     * 产业园
     * @param vehicleId
     * @return
     */
    public Result uploadVehicle(String vehicleId) {
        HyVehicle hyVehiclDb = vehicleService.getById(vehicleId);
        if(hyVehiclDb == null) {
            return Result.error("未找到对应数据");
        }

        HyVehicleReport hyVehicleReport = new HyVehicleReport();

        if (StringUtils.isEmpty(hyVehiclDb.getRoadTransportNumber())) {
            log.error("车辆道路运输证不能为空！{}", hyVehiclDb.getVehicleNumber());
            return Result.error("车辆道路运输证不能为空！");
        }

        if (!vehicleService.checkRTCNoV2(hyVehiclDb)) {
            log.error("车辆道路运输证号不正确或者已过期，请修改后重新上传！{}", hyVehiclDb.getVehicleNumber());
            return Result.error("车辆道路运输证号不正确或者已过期，请修改后重新上传！");
        }

        HyVehicleType hyVehicleType = vehicleService.getHyVehicleType(hyVehiclDb.getVehicleType());
        if (hyVehicleType == null) {
            return Result.error("车辆类型不存在,修改后请重新上报！");
        }

        XzVehicleDTO xzVehicleDTO = new XzVehicleDTO();

        xzVehicleDTO.setVehicleNumber(hyVehiclDb.getVehicleNumber());
        xzVehicleDTO.setVehiclePlateColorCode(hyVehiclDb.getVehiclePlateColorCode());
        xzVehicleDTO.setVehicleType(hyVehicleType.getValue());
        xzVehicleDTO.setOwner(hyVehiclDb.getOwner());
        xzVehicleDTO.setUseCharacter("货运");
        xzVehicleDTO.setVin(hyVehiclDb.getVin());
        xzVehicleDTO.setIssuingOrganizations(hyVehiclDb.getIssuingOrganizations());
        xzVehicleDTO.setVehicleHeight(hyVehiclDb.getVehicleHeight());
        xzVehicleDTO.setVehicleLength(hyVehiclDb.getVehicleLong());
        xzVehicleDTO.setVehicleWidth(hyVehiclDb.getVehicleWidth());
        xzVehicleDTO.setRegisterDate(
                DateUtils.date2Str(hyVehiclDb.getRegisterDate(), DateUtils.date_sdf.get())
        );
        xzVehicleDTO.setIssueDate(
                DateUtils.date2Str(hyVehiclDb.getIssueDate(), DateUtils.date_sdf.get())
        );
        xzVehicleDTO.setVehicleEnergyType(hyVehiclDb.getVehicleEnergyType());
        BigDecimal vehicleTonnage = hyVehiclDb.getVehicleTonnage().multiply(new BigDecimal("100"));
        xzVehicleDTO.setVehicleTonnage(
                vehicleTonnage.setScale(0, BigDecimal.ROUND_DOWN).intValue()
        );
        BigDecimal grossMass = hyVehiclDb.getGrossMass().multiply(new BigDecimal("100"));
        xzVehicleDTO.setGrossMass(
                grossMass.setScale(0, BigDecimal.ROUND_DOWN).intValue()
        );
        xzVehicleDTO.setRoadTransportCertificateNumber(hyVehiclDb.getRoadTransportNumber());

        Calendar cal = Calendar.getInstance();
        cal.setTime(hyVehiclDb.getRegisterDate());
        cal.add(Calendar.YEAR, 10);
        Date validPeriodTo = cal.getTime();

        xzVehicleDTO.setLicenseValidPeriodTo(
                DateUtils.date2Str(validPeriodTo, DateUtils.date_sdf.get())
        );
        Date transportValidPeriodTo = hyVehiclDb.getRoadTransportExpiredDate() != null ?
                hyVehiclDb.getRoadTransportExpiredDate() : validPeriodTo;
        xzVehicleDTO.setTransportValidPeriodTo(
                DateUtils.date2Str(transportValidPeriodTo, DateUtils.date_sdf.get())
        );
        xzVehicleDTO.setVehicleLicenseFirstSheetImg(
                xzIndustrialParkService.uploadFile(uploadpath + File.separator + hyVehiclDb.getDrivingLicenseImg(),
                        hyVehiclDb.getVehicleNumber() + "(行驶证主页照片)")
        );

        String vehicleLicenseSecondSheetImg = xzIndustrialParkService.uploadFile(uploadpath + File.separator + hyVehiclDb.getDrivingLicenseImg2(), hyVehiclDb.getVehicleNumber() + "行驶证副页照片");
        xzVehicleDTO.setVehicleLicenseSecondSheetImg(vehicleLicenseSecondSheetImg);
        xzVehicleDTO.setVehicleLicenseSecondSheetBackImg(vehicleLicenseSecondSheetImg);

        if (StrUtil.isNotEmpty(hyVehiclDb.getRoadTransportImg())) {
            xzVehicleDTO.setTransportLicenseFirstSheetImg(
                    xzIndustrialParkService.uploadFile(uploadpath + File.separator + hyVehiclDb.getRoadTransportImg(), hyVehiclDb.getVehicleNumber() + "(道路运输证照片)")
            );

            xzVehicleDTO.setTransportLicenseSecondSheetImg(
                    xzIndustrialParkService.uploadFile(uploadpath + File.separator + hyVehiclDb.getRoadTransportImg(), hyVehiclDb.getVehicleNumber() + "(道路运输证照片)")
            );
        }

        if (StrUtil.isNotEmpty(hyVehiclDb.getVehicleImg())) {
            xzVehicleDTO.setVehicleDriverImg(
                    xzIndustrialParkService.uploadFile(uploadpath + File.separator + hyVehiclDb.getVehicleImg(), hyVehiclDb.getVehicleNumber() + "(车辆照片)")
            );
        }

        if (StrUtil.isNotEmpty(hyVehiclDb.getTrailerVehiclePlateNumber())) {
            xzVehicleDTO.setTrailerVehiclePlateNumber(hyVehiclDb.getTrailerVehiclePlateNumber());
        }

        try{
            XzApiBaseResDTO xzApiBaseResDTO = xzIndustrialParkService.subjectVehicle(xzVehicleDTO);
            boolean status = xzApiBaseResDTO.isSuccess() && 1001 == xzApiBaseResDTO.getStatus() ;
            String result = xzApiBaseResDTO.getResult() != null ? JSONObject.toJSONString(xzApiBaseResDTO.getResult()) : StringUtils.EMPTY;

            hyVehicleReport.setVehicleId(vehicleId);
            hyVehicleReport.setCompanyId("2000");
            hyVehicleReport.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_XZ.getCode());
            hyVehicleReport.setVehicleUploadStatus(status? "1" : "2");
            hyVehicleReport.setUploadDate( new Date() );
            hyVehicleReport.setVehicleReportFailureReason(status ? "" : xzApiBaseResDTO.getMessage()+result);
            vehicleReportService.saveVehicleReport(hyVehicleReport);

            this.vehicleService.updateYuanquUploadStatusById(vehicleId, hyVehicleReport.getVehicleUploadStatus());
            if (!status) {
                return Result.error(xzApiBaseResDTO.getMessage() + result);
            }

            return Result.OK("上报成功");
        }catch (Exception e){

            hyVehicleReport.setVehicleId(vehicleId);
            hyVehicleReport.setCompanyId("2000");
            hyVehicleReport.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_XZ.getCode());
            hyVehicleReport.setVehicleUploadStatus( "2");
            hyVehicleReport.setUploadDate( new Date() );
            hyVehicleReport.setVehicleReportFailureReason(e.getMessage());
            vehicleReportService.saveVehicleReport(hyVehicleReport);
            throw new JeecgBootException(e.getMessage());
        }
    }


    /**
     * 产业园
     * @param driverId
     * @return
     */
    public Result uploadDriver(String driverId) {
        HyDriver hyDriverDb = driverService.getById(driverId);
        if(hyDriverDb == null) {
            return Result.error("未找到对应数据");
        }

        HyDriverReport hyDriverReport = new HyDriverReport();
        //人员从业资格证验证
        if (!driverService.checkQualificationV2(hyDriverDb)) {
            log.error("人员从业资格证验证号不正确或者已过期，请修改后重新上传！ {} {}", driverId, hyDriverDb.getDriverName());
            return Result.error("人员从业资格证验证号不正确或者已过期，请修改后重新上传！");
        }

        if (StringUtils.isBlank(hyDriverDb.getQualificationImg())) {
            log.error("人员从业资格证不能为空，请重新上传！ {} {}", driverId, hyDriverDb.getDriverName());
            return Result.error("人员从业资格证不能为空，请重新上传！");
        }

        if (null == hyDriverDb.getIdcardExpiredDate()) {
            return Result.error("身份证有效期日期不能为空");
        }

        XzDriverDTO xzDriverDTO = new XzDriverDTO();
        xzDriverDTO.setDriverName(hyDriverDb.getDriverName());
        xzDriverDTO.setDrivingLicense(hyDriverDb.getIdcard());
        xzDriverDTO.setVehicleClass(hyDriverDb.getVehicleClass());
        xzDriverDTO.setIssuingOrganizations(hyDriverDb.getIssuingOrganizations());
        xzDriverDTO.setValidPeriodFrom(
                DateUtils.date2Str(hyDriverDb.getValidPeriodFrom(), DateUtils.date_sdf.get())
        );
        xzDriverDTO.setValidPeriodTo(
                DateUtils.date2Str(hyDriverDb.getValidPeriodTo(), DateUtils.date_sdf.get())
        );
        xzDriverDTO.setQualificationCertificate(
                StringUtils.isNotEmpty(hyDriverDb.getQualificationCertificate()) ? hyDriverDb.getQualificationCertificate() : hyDriverDb.getDrivingLicense()
        );
        xzDriverDTO.setTelephone(hyDriverDb.getTelephone());
        xzDriverDTO.setRemark("备注");
        xzDriverDTO.setIdCardFrontImg(
                xzIndustrialParkService.uploadFile(uploadpath + File.separator + hyDriverDb.getIdcardImg(), "司机 " + hyDriverDb.getDriverName() + "(身份证人像面图片)")
        );
        xzDriverDTO.setIdCardBackImg(
                xzIndustrialParkService.uploadFile(uploadpath + File.separator + hyDriverDb.getIdcardImgBack(), "司机 " + hyDriverDb.getDriverName() + "(身份证人像面图片)")
        );
        xzDriverDTO.setIdCardValidPeriodTo(
                DateUtils.date2Str(hyDriverDb.getIdcardExpiredDate(), DateUtils.date_sdf.get())
        );
        xzDriverDTO.setTransportCertificationValidPeriodTo(
                DateUtils.date2Str(hyDriverDb.getIdcardExpiredDate(), DateUtils.date_sdf.get())
        );

        xzDriverDTO.setDriverLicenseFirstSheetImg(
                xzIndustrialParkService.uploadFile(uploadpath + File.separator + hyDriverDb.getDriverImg(), "司机 " + hyDriverDb.getDriverName() + "(驾驶证主页照片)")
        );
        if (StringUtils.isNotBlank(hyDriverDb.getDriverImg2())) {
            xzDriverDTO.setDriverLicenseSecondSheetImg(
                    xzIndustrialParkService.uploadFile(uploadpath + File.separator + hyDriverDb.getDriverImg2(), "司机 " + hyDriverDb.getDriverName() + "(驾驶证副页照片)")
            );
        }

        xzDriverDTO.setTransportCertificationImg(
                xzIndustrialParkService.uploadFile(uploadpath + File.separator + hyDriverDb.getQualificationImg(), "司机 " + hyDriverDb.getDriverName() + "(从业资格证照片)")
        );
        xzDriverDTO.setDriverSex(1);
        xzDriverDTO.setDriverBirthday(
                IDUtils.getIdBirthdayString(hyDriverDb.getIdcard())
        );

        try{
            XzApiBaseResDTO xzApiBaseResDTO = xzIndustrialParkService.subjectDriver(xzDriverDTO);
            boolean status =  xzApiBaseResDTO.isSuccess() && 1001 == xzApiBaseResDTO.getStatus() ;
            String result = xzApiBaseResDTO.getResult() != null ? JSONObject.toJSONString(xzApiBaseResDTO.getResult()) : StringUtils.EMPTY;
            hyDriverReport.setDriverId(driverId);
            //上传中交园区写死固定公司ID
            hyDriverReport.setCompanyId("2000");
            hyDriverReport.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_XZ.getCode());
            hyDriverReport.setDriverUploadStatus(status ? "1" : "2");
            hyDriverReport.setUploadDate( new Date() );
            hyDriverReport.setDriverReportFailureReason( status ? "" : xzApiBaseResDTO.getMessage()+result );
            hyDriverReportService.saveDriverReport(hyDriverReport);

            this.driverService.updateYqUploadStatusById(driverId, hyDriverReport.getDriverUploadStatus());
            if (!status) {
                return Result.error(xzApiBaseResDTO.getMessage() + result);
            }

            return Result.OK("上报成功");
        }catch (Exception e){
            hyDriverReport.setDriverId(driverId);
            hyDriverReport.setCompanyId("2000");
            hyDriverReport.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_XZ.getCode());
            hyDriverReport.setDriverUploadStatus( "2");
            hyDriverReport.setUploadDate( new Date() );
            hyDriverReport.setDriverReportFailureReason( e.getMessage());
            hyDriverReportService.saveDriverReport(hyDriverReport);
            throw new JeecgBootException(e.getMessage());
        }
    }

    //region 2024-06-26 for 新增实际承运人与车辆绑定操作
    private Result uploadCarrier(HyDriver hyDriverDb) {

        HyCarrierReport hyCarrierReport = new HyCarrierReport();

        JSONObject jsonObject = new JSONObject();
        String idCardFrontImg = this.xzIndustrialParkService.uploadFile(
                uploadpath + File.separator + hyDriverDb.getIdcardImg(), "司机 " + hyDriverDb.getDriverName() + "(身份证正面图片)");
        String idCardBackImg = this.xzIndustrialParkService.uploadFile(
                uploadpath + File.separator + hyDriverDb.getIdcardImgBack(), "司机 " + hyDriverDb.getDriverName() + "(身份证反面图片)");

        jsonObject.put("carrierName", hyDriverDb.getDriverName());
        jsonObject.put("carrierLicense", hyDriverDb.getIdcard());
        jsonObject.put("idCardFrontImg", idCardFrontImg);
        jsonObject.put("idCardBackImg", idCardBackImg);

        try{
            XzApiBaseResDTO xzApiBaseResDTO = xzIndustrialParkService.subjectCarrier(jsonObject);
            boolean status = xzApiBaseResDTO.isSuccess() && 1001 == xzApiBaseResDTO.getStatus() ;
            String result = xzApiBaseResDTO.getResult() != null ? JSONObject.toJSONString(xzApiBaseResDTO.getResult()) : StringUtils.EMPTY;
            hyCarrierReport.setCarrierId(hyDriverDb.getId());
            //上传中交园区写死固定公司ID
            hyCarrierReport.setCompanyId("2000");
            hyCarrierReport.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_XZ.getCode());
            hyCarrierReport.setCarrierUploadStatus(status ? "1" : "2");
            hyCarrierReport.setUploadDate( new Date() );
            hyCarrierReport.setCarrierReportFailureReason( status ? "" : xzApiBaseResDTO.getMessage()+result );
            this.hyCarrierReportService.saveCarrierReport(hyCarrierReport);
            if (!status) {
                return Result.error(xzApiBaseResDTO.getMessage() + result);
            }

            return Result.OK("上报成功");
        }catch (Exception e){
            hyCarrierReport.setCarrierId(hyDriverDb.getId());
            hyCarrierReport.setCompanyId("2000");
            hyCarrierReport.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_XZ.getCode());
            hyCarrierReport.setCarrierUploadStatus( "2");
            hyCarrierReport.setUploadDate( new Date() );
            hyCarrierReport.setCarrierReportFailureReason( e.getMessage());
            this.hyCarrierReportService.saveCarrierReport(hyCarrierReport);
            throw new JeecgBootException(e.getMessage());
        }
    }


    private Result uploadCarrierVehicle(HyDriver hyDriverDb, HyVehicle hyVehicleDb) {

        JSONObject jsonObject = new JSONObject();
        //String idCardFrontImg = this.xzIndustrialParkService.uploadFile(
        //        uploadpath + File.separator + hyDriverDb.getIdcardImg(), "司机 " + hyDriverDb.getDriverName() + "(身份证正面图片)");

        jsonObject.put("carrierLicense", hyDriverDb.getIdcard()); //承运人身份证号
        jsonObject.put("vehicleNumber", hyVehicleDb.getVehicleNumber()); //车辆牌照号
        //jsonObject.put("ownershipFile", hyVehicleDb.getAffiliationAgreement());

        try {
            XzApiBaseResDTO xzApiBaseResDTO = xzIndustrialParkService.subjectCarrierVehicle(jsonObject);
            boolean status = xzApiBaseResDTO.isSuccess() && 1001 == xzApiBaseResDTO.getStatus() ;
            String result = xzApiBaseResDTO.getResult() != null ? JSONObject.toJSONString(xzApiBaseResDTO.getResult()) : StringUtils.EMPTY;
            //上传中交园区写死固定公司ID
            this.hyCarrierReportService.update(new LambdaUpdateWrapper<HyCarrierReport>()
                    .eq(HyCarrierReport::getCarrierId, hyDriverDb.getId())
                    .eq(HyCarrierReport::getCompanyId, "2000")
                    .eq(HyCarrierReport::getReportPlatformType, ReportPlatformEnum.REPORT_PLATFORM_XZ.getCode())
                    .set(HyCarrierReport::getCarrierVehicleUploadStatus, status ? "1" : "2")
                    .set(HyCarrierReport::getCarrierVehicleReportFailureReason, status ? "" : xzApiBaseResDTO.getMessage()+result)
            );
            if (!status) {
                return Result.error(xzApiBaseResDTO.getMessage() + result);
            }

            return Result.OK("上报成功");
        } catch (Exception e) {
            this.hyCarrierReportService.update(new LambdaUpdateWrapper<HyCarrierReport>()
                    .eq(HyCarrierReport::getCarrierId, hyDriverDb.getId())
                    .eq(HyCarrierReport::getCompanyId, "2000")
                    .eq(HyCarrierReport::getReportPlatformType, ReportPlatformEnum.REPORT_PLATFORM_XZ.getCode())
                    .set(HyCarrierReport::getCarrierVehicleUploadStatus, "2")
                    .set(HyCarrierReport::getCarrierVehicleReportFailureReason, e.getMessage())
            );

            throw new JeecgBootException(e.getMessage());
        }
    }

    private Result uploadCarrierDriver(HyDriver hyDriverDb) {

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("carrierLicense", hyDriverDb.getIdcard()); //承运人身份证号
        jsonObject.put("driverLicense", hyDriverDb.getIdcard()); //驾驶员身份证号

        try {
            XzApiBaseResDTO xzApiBaseResDTO = xzIndustrialParkService.subjectCarrierDriver(jsonObject);
            boolean status = xzApiBaseResDTO.isSuccess() && 1001 == xzApiBaseResDTO.getStatus() ;
            String result = xzApiBaseResDTO.getResult() != null ? JSONObject.toJSONString(xzApiBaseResDTO.getResult()) : StringUtils.EMPTY;
            //上传中交园区写死固定公司ID
            this.hyCarrierReportService.update(new LambdaUpdateWrapper<HyCarrierReport>()
                    .eq(HyCarrierReport::getCarrierId, hyDriverDb.getId())
                    .eq(HyCarrierReport::getCompanyId, "2000")
                    .eq(HyCarrierReport::getReportPlatformType, ReportPlatformEnum.REPORT_PLATFORM_XZ.getCode())
                    .set(HyCarrierReport::getCarrierDriverUploadStatus, status ? "1" : "2")
                    .set(HyCarrierReport::getCarrierDriverReportFailureReason, status ? "" : xzApiBaseResDTO.getMessage()+result)
            );
            if (!status) {
                return Result.error(xzApiBaseResDTO.getMessage() + result);
            }

            return Result.OK("上报成功");
        } catch (Exception e) {
            this.hyCarrierReportService.update(new LambdaUpdateWrapper<HyCarrierReport>()
                    .eq(HyCarrierReport::getCarrierId, hyDriverDb.getId())
                    .eq(HyCarrierReport::getCompanyId, "2000")
                    .eq(HyCarrierReport::getReportPlatformType, ReportPlatformEnum.REPORT_PLATFORM_XZ.getCode())
                    .set(HyCarrierReport::getCarrierDriverUploadStatus, "2")
                    .set(HyCarrierReport::getCarrierDriverReportFailureReason, e.getMessage())
            );

            throw new JeecgBootException(e.getMessage());
        }
    }
    //endregion



    //region 园区数据上报校验
    /**
     * 运单校验结果查询接口
     * @param hyShippingNote
     * @return
     */
    @Override
    public Result validateShippingNote(HyShippingNote hyShippingNote) {
        if (hyShippingNote == null) {
            return Result.error("运单信息不存在!");
        }

        HyShippingParkReport existParkReport = this.hyShippingParkReportService.getById(hyShippingNote.getId());
        if (null == existParkReport) {
            return Result.error("请先上报运单和资金流水数据到园区平台");
        }

        //1表示上报成功，3表示等待校验，如果不是这2个状态说明运单没有上报过
        if (!"1".equals(existParkReport.getUploadStatus()) && !"3".equals(existParkReport.getUploadStatus())) {
            return Result.error("请先上报运单数据到园区监管平台");
        }

        //1表示上报成功，3表示等待校验，如果不是这2个状态说明资金流水没有上报过
        if (!"1".equals(existParkReport.getZjUploadStatus()) && !"3".equals(existParkReport.getZjUploadStatus())) {
            return Result.error("请先上报资金流水数据到园区监管平台");
        }

        List <TransportValidateParamDTO> transportValidateParamDTOS = Collections.singletonList(
                new TransportValidateParamDTO()
                        .setShippingNoteNumber(hyShippingNote.getShippingNoteNumber())
                        .setSerialNumber("0000")
        );
        XzApiBaseResDTO  xzApiBaseResDTO = xzIndustrialParkService.validateTransport(transportValidateParamDTOS);
        if(xzApiBaseResDTO.isSuccess() && 1001 == xzApiBaseResDTO.getStatus()){

            String result = JSONObject.toJSONString(xzApiBaseResDTO.getResult());
            if(StringUtils.isBlank(result)){
                return Result.error("校验运单异常请稍后再试");
            }
            List<TransportValidateDTO> transportValidateDTOS = JSONObject.parseArray(result, TransportValidateDTO.class);
            TransportValidateDTO transportValidateDTO = transportValidateDTOS.get(0);
            log.info("园区校验运单, {} {}", hyShippingNote.getShippingNoteNumber(), JSONUtil.toJsonStr(transportValidateDTO));
            if (transportValidateDTO.getValidateStatus().contains("通过") ) {
                existParkReport.setUploadStatus("1");
                existParkReport.setFailureReason("通过");
                this.hyShippingParkReportService.updateById(existParkReport);
                return Result.OK();
            } else if("异常".equals(transportValidateDTO.getValidateStatus())) {

                List<ValidateResult> validateResults = transportValidateDTO.getValidateResult().stream()
                        .filter(a -> a.getFlag().equals("异常")).collect(
                                Collectors.toList());
                existParkReport.setUploadStatus("3");
                existParkReport.setFailureReason("校验失败: " + JSONObject.toJSONString(validateResults));
                this.hyShippingParkReportService.updateById(existParkReport);
                return Result.error("校验失败: "+JSONObject.toJSONString(validateResults));
            } else {
                return Result.error("校验失败: "+transportValidateDTO.getValidateStatus());
            }
        } else {
            existParkReport.setUploadStatus("2");
            this.hyShippingParkReportService.updateById(existParkReport);
            String result = JSONObject.toJSONString(xzApiBaseResDTO.getResult());
            return Result.error(xzApiBaseResDTO.getMessage()+": "+result);
        }
    }


    /**
     * 运单申诉接口
     * @param appealDTO
     * @return
     */
    @Override
    public Result appealShippingNote(AppealDTO appealDTO){
        HyShippingNote hyShippingNote = hyShippingNoteService.queryByShippingNoteNumber(appealDTO.getTransportNumber());
        if (hyShippingNote == null) {
            return Result.error("运单信息不存在!");
        }

        HyShippingParkReport hyShippingParkReport = this.hyShippingParkReportService.getById(hyShippingNote.getId());
        if (null == hyShippingParkReport) {
            return Result.error("请先上报运单数据到园区");
        }

        String appealImg = xzIndustrialParkService.uploadFile(uploadpath + File.separator +appealDTO.getAppealImg(), "申诉图片");
        appealDTO.setAppealImg(appealImg);
        XzApiBaseResDTO  xzApiBaseResDTO = xzIndustrialParkService.transportAppeal(appealDTO );
        if(xzApiBaseResDTO.isSuccess() && 1001 == xzApiBaseResDTO.getStatus()){
            hyShippingParkReport.setAppealStatus("2");
            hyShippingParkReport.setAppealReason("申诉成功待审核");
            hyShippingParkReport.setAppealDate(new Date());
            this.hyShippingParkReportService.updateById(hyShippingParkReport);
            return Result.OK("申诉完成");
        }

        hyShippingParkReport.setAppealStatus("3");
        hyShippingParkReport.setAppealReason(xzApiBaseResDTO.getMessage());
        hyShippingParkReport.setAppealDate(new Date());
        this.hyShippingParkReportService.updateById(hyShippingParkReport);
        return Result.error(xzApiBaseResDTO.getMessage());
    }


    /**
     * 运单申诉结果查询接口
     * @return
     */
    @Override
    public Result appealShippingNoteQuery(String shippingId) {
        HyShippingNote hyShippingNote = hyShippingNoteService.getById(shippingId);
        if(hyShippingNote == null){
            return Result.error("运单信息不存在!");
        }

        HyShippingParkReport hyShippingParkReport = this.hyShippingParkReportService.getById(hyShippingNote.getId());
        if (null == hyShippingParkReport) {
            return Result.error("请先上报运单数据到园区");
        }
        if (StrUtil.isEmpty(hyShippingParkReport.getAppealStatus()) || "0".equals(hyShippingParkReport.getAppealStatus())) {
            return Result.error("未找到有效的运单申诉记录");
        }

        XzApiBaseResDTO  xzApiBaseResDTO = xzIndustrialParkService.transportAppealQuery(new AppealDTO()
                .setTransportNumber(hyShippingNote.getShippingNoteNumber())
                .setSerialNumber("0000")
        );
        if(xzApiBaseResDTO.isSuccess() && 1001 == xzApiBaseResDTO.getStatus()){
            String  result = JSONObject.toJSONString(xzApiBaseResDTO.getResult());
            if(StringUtils.isBlank(result)){
                return Result.error("运单申诉查询出错,请稍后再试");
            }
            AppealRespDTO appealRespDTO = JSON.parseObject(result, AppealRespDTO.class);
            hyShippingNote.setAppealStatus( String.valueOf(appealRespDTO.getAppealStatus()));
            hyShippingNoteService.updateById(hyShippingNote);
            if(3 == appealRespDTO.getAppealStatus() ){
                hyShippingParkReport.setAppealStatus("1");
                hyShippingParkReport.setAppealReason("申诉成功");
                hyShippingParkReport.setAppealDate(new Date());
                this.hyShippingParkReportService.updateById(hyShippingParkReport);
                return Result.OK("申诉成功");
            }else {
                return Result.error("当前运单申诉结果: "+appealRespDTO.getAppealStatusName());
            }
        }else {
            return Result.error(xzApiBaseResDTO.getMessage());
        }
    }
    //endregion


}
